﻿using System;
using System.Web.Mvc;
using BLL.Installer;
using BLL.Interface.Menu;
using BLL.Model.Menu;
using BLL.Utility;
using WayCloud.ViewModel;
using WayCloud.ViewModel.Menu;

namespace WayCloud.Controllers.Menu
{
    [Authorize(Roles = "admin")]
    public class MenuController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult List(MenuCondition condition)
        {
            if (!ModelState.IsValid)
            {
                return null;
            }
            AnalyseJqGridQueryString ajqs = new AnalyseJqGridQueryString(Request.QueryString);
            var page = ajqs.GetPageInfo();
            var sort = new Tuple<string, string>("order", "asc");
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var menuList = menuInfoManager.GetMenuInfoByFilter(condition, sort, page);
            var result = new JqGrid(page, menuList);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult FindMenuInfoById(int id)
        {
            if (id==0)
            {
                return View("Add");
            }
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var result = menuInfoManager.FindMenuInfoById(id);
            return View("Edit", result);
        }

        public ActionResult Edit(MenuInfo info)
        {
            if (!ModelState.IsValid)
            {
                return View(info);
            }
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var result = menuInfoManager.UpdateMenuInfo(info);
            return result ? Content("ok") : View(info) as ActionResult;
        }

        public ActionResult Add([Bind(Exclude = "Order")]MenuInfo info)
        {
            if (!ModelState.IsValid)
            {
                return View(info);
            }
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var result = menuInfoManager.AddMenuInfo(info);
            return result ? Content("ok") : View(info) as ActionResult;
        }

        [HttpGet]
        public ActionResult ReOrder(int id1,int id2)
        {
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var result = menuInfoManager.ReOrder(id1, id2);
            return result ? Content("ok") : Content("error");
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            IMenuInfo menuInfoManager = ContainerHelper.Instance.Container.Resolve<IMenuInfo>();
            var result = menuInfoManager.DeleteMenuInfoById(id);
            return result ? Content("ok") : Content("error");
        }

    }
}
